package com.ninelock.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: JsonUtils @Description: json工具类
 *
 * @author: gongym
 * @date: 2017年10月13日 上午8:57:20
 */
public class JsonUtils {
  private static final ObjectMapper MAPPER = new ObjectMapper();
  /** 序列化中的时间格式化 */
  private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

  /**
   * @Title: objectToJson @Description: 将对象转换成json字符串
   *
   * @param data
   * @return
   * @return: String
   */
  public static String objectToJson(Object data) {
    try {
      MAPPER.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_FORMAT));
      return MAPPER.writeValueAsString(data);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * @Title: objectToJson @Description: 自定义事件格式化的JSON转换
   *
   * @param data
   * @param dateFormat
   * @return
   * @return: String
   */
  public static String objectToJson(Object data, String dateFormat) {
    try {
      MAPPER.setDateFormat(new SimpleDateFormat(dateFormat));
      return MAPPER.writeValueAsString(data);
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * @Title: jsonToPojo @Description: 将json结果集转化为对象
   *
   * @param jsonData
   * @param beanType
   * @return
   * @return: T
   */
  public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
    try {
      return MAPPER.readValue(jsonData, beanType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * @Title: jsonToList @Description: 将json数据转换成pojo对象list
   *
   * @param jsonData
   * @param beanType
   * @return
   * @return: List<T>
   */
  public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    try {
      return MAPPER.readValue(jsonData, javaType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static <T> List<T> jsonToList(String jsonData) {
    JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, Map.class);
    try {
      return MAPPER.readValue(jsonData, javaType);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  /**
   * @Title: jsonToMap @Description: 将json数据转换成map
   *
   * @param jsonData
   * @return
   * @return: HashMap<Object,Object>
   */
  public static HashMap<Object, Object> jsonToMap(String jsonData) {
    try {
      return MAPPER.readValue(jsonData, new TypeReference<HashMap<Object, Object>>() {});
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
